<?php
namespace app\tabbar\model;

use think\Model;
use app\tabbar\model\TabbarType as TabbarTypeModel;

class Tabbar extends Model
{
    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';

    // 自动写入时间戳
    protected $autoWriteTimestamp = true;

    public function initialize()
    {
        parent::initialize();
        if (!isset($this->modelKey) || empty($this->modelKey) || cache('modelKey') != $this->modelKey) {
            exit(json_encode(['msg'=>'非法操作！','code'=>711]));
        }
    }

    /**
     * 列表
     * @param array $map
     * @param int $page
     * @param int $limit
     * @param string $order
     * @param bool|true $field
     * @return mixed
     */
    public function getList ($map = [], $page = 0, $limit = 10, $order = "sort asc, create_time desc", $field = true) {
        $key = md5(json_encode($map). $page . $limit . $order . $field . request()->baseFile() .request()->controller() . request()->action() . request()->module());
        $ret = cache($key);
        if ($ret && strstr(request()->baseFile(), 'api.php')) {
            return $ret;
        }
        $obj = $this->where($map)->field($field)->orderRaw($order);
        $ret = [];
        $ret['count'] = (int)$obj->count();
        $ret['page'] = (int)$page;
        $ret['limit'] = (int)$limit;
        if($page) {
            $obj = $obj->page($page)->limit($limit);
        }
        $obj = $obj->select();
        if (!$obj) return [];
        $ret['list'] = $obj->append(['TidName'])->toArray();
        cache($key, $ret, 600);
        return $ret;
    }

    public function getTidNameAttr($v, $d)
    {
        return (new TabbarTypeModel)->where('id', $d['tid'])->value('name');
    }

}